package com.hyjiacan.tools

import com.hyjiacan.tools.apps.apitool.handlers.ApiTestHandler
import com.hyjiacan.tools.apps.dbm.handlers.ConnectionHandler
import com.hyjiacan.tools.apps.dbm.handlers.DatabaseHandler
import com.hyjiacan.tools.apps.dbm.utils.Misc
import com.hyjiacan.tools.http.handlers.SecurityHandler
import com.hyjiacan.tools.http.handlers.StaticHandler
import com.sun.net.httpserver.HttpServer
import com.sun.org.apache.xml.internal.serializer.utils.Utils.messages
import com.xenomachina.argparser.ArgParser
import com.xenomachina.argparser.HelpFormatter
import com.xenomachina.argparser.ShowHelpException
import com.xenomachina.argparser.mainBody
import java.io.Console
import java.net.InetSocketAddress
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.concurrent.Executors
import kotlin.concurrent.thread


open class Application {

    companion object {
        @JvmStatic
        fun main(args: Array<String>) = mainBody {
            ArgParser(args).parseInto(::Options).run {
                println("使用 --help 查看帮助信息")
                println("------------------------")
                if (showNginxConf) {
                    printNginxConf(host, port)
                    return@mainBody
                }

                val addr = InetSocketAddress(host, port)
                val server = HttpServer.create(addr, 0)

                server.createContext("/api/v1/security", SecurityHandler())

                server.createContext("/api/v1/connection", ConnectionHandler())
                server.createContext("/api/v1/database", DatabaseHandler())

                server.createContext("/api/v1/testapi", ApiTestHandler())

                server.createContext("/", StaticHandler())

                server.executor = Executors.newFixedThreadPool(10)

                server.start()
                println("WebDBM is running at http://$host:$port")

                runThread()
            }
        }

        private fun getDate(): String {
            return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        }

        private fun runThread() {
            thread(start = true, name = "task") {
                // 启动时执行一次
                runTask()

                var lastDate = getDate()
                while (!Thread.interrupted()) {
                    try {
                        // 每小时1次
                        Thread.sleep(1000 * 60 * 60)

                        // 获取今天的日期
                        val today = getDate()

                        // 每天只执行一次
                        if (lastDate != today) {
                            lastDate = today
                            runTask()
                        }
                    } catch (e: InterruptedException) {
                        // 线程被中断，优雅退出
                        break
                    }
                }
            }
        }

        /**
         * 执行其它任务
         */
        private fun runTask() {
            try {
                // 清除临时文件
                val tempPath = Misc.getTmpPath()
                Misc.deleteDirectoryRecursively(tempPath, false)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        private fun printNginxConf(host: String, port: Int) {
            val conf = "location /webdbm/ {\n" +
                    "    proxy_pass  http://$host:$port/;\n" +
                    "    proxy_set_header Host \$proxy_host;\n" +
                    "    proxy_set_header X-Real-IP \$remote_addr;\n" +
                    "    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;\n" +
                    "    proxy_read_timeout 60s;\n" +
                    "}"

            println(conf)
        }
    }

}